﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Web;

namespace Google.Translates.Core
{
    public class TranslatorByBingHttp : TranslatorByHttp
    {
        protected string m_AppId;

        public TranslatorByBingHttp()
        {
            m_AppId = ApiSetting.GetBingTranslateAppId();
        }

        public List<string> BreakSentences(string text, string trgLangKey)
        {
            var reVal = new List<string>();
            var srcWords = HttpUtility.UrlEncode(text);
            string uri = "http://api.microsofttranslator.com/v2/Http.svc/BreakSentences?appid=" + m_AppId + "&text=" +srcWords;
            if (!string.IsNullOrEmpty(trgLangKey))
                uri += "&language=" + trgLangKey;
            var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri);
            WebResponse response = null;
            try
            {
                response = httpWebRequest.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    var dcs = new DataContractSerializer(typeof (List<int>));
                    var result = (List<int>) dcs.ReadObject(stream);
                    var startIndex = 0;
                    for (int i = 0; i < result.Count; i++)
                    {
                        reVal.Add(text.Substring(startIndex, result[i]));
                        startIndex += result[i];
                    }
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            return reVal;
        }
    }


}